<template>
  <div>
    <div class="tag">
      <div>
        <el-divider style="font-weight:900;width:80px" content-position="left">岗位标签</el-divider>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="addtag">新增标签</el-button>
      </div>
      <div class="nav">
        <div v-for="(item,index) in employees " :key="index" shadow="never" style="background:#f5f8ff;width:294px;margin-bottom:10px;min-height:95px;margin-right:10px;border-radius:6px">
          <div slot="header" class="clearfix" style="display:flex;align-items:flex-start;margin-top:10px;height:19px">
            <p style="width:210px;height:16px;margin-left:12px;display:flex">
              <span class="iconfont icon_biaoqian" style="color:#0076CB" />
              <el-popover placement="bottom" style="color:#0076CB;font-size:16px;margin-left:9px" width="90px" trigger="hover" :content="item.name">
                <span slot="reference" style="width:184px;display:inline-block;line-height:18px" class="table_name">{{ item.name }}</span>
              </el-popover>
            </p>
            <p style="display:flex;align-items:flex-start">
              <el-button type="text" size="medium" icon="el-icon-delete" style="margin-left:11px;padding-top:0px;color:#DADADA;font-size:16px" @click="deleteE(item)" />
              <el-button type="text" size="medium" icon="iconfont icon_xiugai" style="padding-top:0px;color:#DADADA;font-size:16px" @click="editE(item)" />
            </p>
          </div>
          <div class="text item" style="margin-top:13px" @click="check(index)">
            <el-popover placement="bottom" style="color:#616161;font-size:12px;margin-left:38px" trigger="hover" :content="item.description" width="260">
              <span slot="reference" class="table_name" style="color:#999999;font-size:12px;width:230px;display:inline-block">{{ item.description }}</span>
            </el-popover>
          </div>
          <div style="margin-left:38px;color:#616161;margin-top:3px">
            <span v-for="(item1, index1) in item.employeeTagEmployeeTypes" :key="index1" style="margin-right:10px">
              <span v-if="item1.employeeTypeCode === 'Coach'" style="font-size:14px;color:#616161">{{ '教练业务' }}</span>
              <span v-if="item1.employeeTypeCode === 'Sale'" style="font-size:14px;color:#616161">{{ '销售业务' }}</span>
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="role" style="margin-top:10px">
      <div style="margin-top:20px">
        <el-divider style="font-weight:900;width:80px" content-position="left">角色</el-divider>
        <el-button type="warning" icon="el-icon-circle-plus-outline" size="mini" @click="addrole">新增角色</el-button>
      </div>
      <div class="nav">
        <div v-for="(item,index) in roles " :key="index" shadow="never" style="background:#FFF9F5;width:294px;margin-bottom:10px;min-height:95px;margin-right:10px;border-radius:6px">
          <div slot="header" class="clearfix" style="display:flex;align-items:flex-start;margin-top:10px;height:19px">
            <p style="width:210px;height:18px;margin-left:12px;display:flex">
              <span class="iconfont icon_biaoqian" style="color:#ffba00" />
              <el-popover placement="bottom" style="color:#ffba00;font-size:16px;margin-left:9px" trigger="hover" width="90px" :content="item.displayName">
                <span slot="reference" style="width:184px;display:inline-block" class="table_name">{{ item.displayName }}</span>
              </el-popover>
            </p>
            <p style="display:flex;align-items:flex-start">
              <el-button type="text" size="medium" icon="el-icon-delete" style="margin-left:11px;padding-top:0px;color:#DADADA;font-size:16px" @click="deleteRole(item)" />
              <el-button type="text" size="medium" icon="iconfont icon_xiugai" style="padding-top:0px;color:#DADADA;font-size:16px" @click="bianji(item)" />
            </p>
          </div>
          <div class="text item" style="margin-top:13px" @click="checkj(index)">
            <el-popover placement="bottom" style="color:#999999;font-size:12px;margin-left:38px" trigger="hover" :content="item.description" width="260">
              <span slot="reference" class="table_name" style="color:#999999;font-size:12px;width:230px;display:inline-block">{{ item.description }}</span>
            </el-popover>
          </div>
          <div style="display:flex" class="btn">
            <el-button type="text" style="color:#616161;font-size:14px;margin-left:36px;height:20px" @click="permissions(item)">查看权限</el-button><el-button type="text" style="font-size:14px;color:black;margin-top:1px;color:#616161;" icon="iconfont icon_a-quanxian11" @click="permissions(item)" />
          </div>
        </div>
      </div>
    </div>
    <!-- 新增标签 -->
    <el-dialog
      :title="Tag"
      class="gl_dialog_TitleLine gl_dl_footer card"
      :visible.sync="dialogTagVisible"
      :close-on-click-modal="false"
      width="462px"
      top="25vh"
    >
      <el-scrollbar>
        <el-form ref="formName" label-width="90px" label-position="right" :model="CreateEmployeeTagInput">
          <el-row>
            <el-col>
              <el-form-item label="标签名称" prop="name" :rules="{ required: true,message :'请输入',trigger:'blur'}">
                <el-input v-model="CreateEmployeeTagInput.name" style="width:256px" size="mini" maxlength="16" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="标签描述">
                <el-input v-model="CreateEmployeeTagInput.description" type="textarea" style="width:256px" size="mini" maxlength="60" rows="4" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="业务设置">
                <el-checkbox-group v-model="employeeTypeCode">
                  <el-checkbox label="Coach">教练业务</el-checkbox>
                  <el-checkbox label="Sale">销售业务</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button size="mini" @click="downEmployee">{{ $t('button.cancel') }}</el-button>
        <!-- 编辑的保存按钮 -->
        <el-button size="mini" type="primary" :loading="addtagg" @click="addEmployee('formName')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新加角色 -->
    <el-dialog
      :title="roletag"
      class="gl_dialog_TitleLine gl_dl_footer card"
      :visible.sync="dialogRoleVisible"
      :close-on-click-modal="false"
      width="1115px"
      top="25vh"
    >
      <el-scrollbar>
        <el-form ref="formName1" label-width="70px" label-position="left" :model="CreateRoleInput">
          <el-row>
            <el-col>
              <el-form-item label="角色" prop="displayName" :rules="{ required: true,message :'请输入',trigger:'blur'}">
                <el-input v-model="CreateRoleInput.displayName" style="width:256px" size="mini" maxlength="16" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="标签描述">
                <el-input v-model="CreateRoleInput.description" type="textarea" style="width:256px" size="mini" maxlength="60" rows="5" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <p style="height:1px;background-color:rgb(158, 152, 152);margin-bottom:20px" />
              <span style="font-size:16px">功能权限在</span>
              <el-select v-model="role" style="margin-left:15px;margin-right:15PX;margin-top:16PX;width:361px" @change="selectid">
                <el-option v-for="(item,index) in roles" :key="index" :label="item.displayName" :value="item.id" />
              </el-select>
              <span style="font-size:16px">的基础上编辑权限</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="tree">
                <div v-for="(item,index) in userList" :key="index" style="width:251px;height:328px;border:1px solid rgb(158, 152, 152);margin-right:10px;margin-top:16px;overflow:auto;border-radius:4px;">
                  <el-tree
                    ref="rightsTree"
                    style="margin-top:10px"
                    :data="userList[index]"
                    :props="defaultProps"
                    show-checkbox
                    node-key="code"
                    :default-expanded-keys="codeList"
                    :default-checked-keys="codeList"
                    @check="checkCode"
                    @check-change="code(index)"
                  />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button size="mini" @click="downRoles">{{ $t('button.cancel') }}</el-button>
        <!-- 编辑的保存按钮 -->
        <el-button size="mini" type="primary" :loading="addroles" @click="editRoles('formName1')">确 定</el-button>
      </span>
    </el-dialog>
    <Permissions ref="permiss" />
  </div>
</template>

<script>
import Permissions from './editStaff/permissions.vue';
import { api_POST_ClubEmployeeTag, api_GET_ClubEmployeeTag, api_DELETE_ClubEmployeeTagId, api_PUT_ClubEmployeeTagId, api_GET_ClubEmployeeTagId } from '@/extend/api/hallswaggerApi/app.js';
import { CreateEmployeeTagInput, Api_GET_ClubEmployeeTagQO, Api_GET_ClubEmployeeTagIdQO } from '@/lib/form/hall/swaggerForm';
import { api_POST_RolesCreate, api_DELETE_RolesId, api_GET_Roles, api_PUT_RolesUpdateId, api_GET_RolesPermissionGroupsId } from '@/extend/api/swaggerApi/identity';
import { Api_GET_RolesQO, CreateRoleInput } from '@/lib/form/swaggerForm';
import { mapState } from 'vuex';
export default {
  components: {
    Permissions
  },
  data() {
    return {
      employeeTypeCode: [],
      roletag: '新增',
      addroles: false,
      addtagg: false,
      Tag: '新增',
      currentPage: 1,
      Eid: '',
      Api_GET_ClubEmployeeTagIdQO: new Api_GET_ClubEmployeeTagIdQO(),
      Api_GET_ClubEmployeeTagQO: new Api_GET_ClubEmployeeTagQO(), // 标签列表
      ff: [],
      CreateEmployeeTagInput: new CreateEmployeeTagInput(), // 创建标签
      creatorId: '', // 角色id
      codeindex: 0,
      a: [],
      codeList: [], // 角色权限code
      newcodeList: [], // 角色权限code
      role: '', // 单个角色
      CreateRoleInput: new CreateRoleInput(), // 创建角色
      roles: [], // 角色
      employees: [], // 标签
      Api_GET_RolesQO: new Api_GET_RolesQO(), // 角色列表
      userList: [], // 角色权限
      active: '',
      active1: '',
      dialogTagVisible: false,
      dialogRoleVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  computed: {
    ...mapState({
      user: state => state.user.info.permissionGroups
    })
  },
  created() {
    // 对权限排序
    for (var i = 0; i < JSON.parse(JSON.stringify(this.user)).length; i += JSON.parse(JSON.stringify(this.user)).length) {
      this.userList.push(JSON.parse(JSON.stringify(this.user)).slice(i, i + JSON.parse(JSON.stringify(this.user)).length));
    }
    console.log(this.user);
    // 获取角色列表
    this.getRoles();
    this.getEmploy();
  },
  methods: {
    // 选中数据
    checkCode(a, code) {
      this.newcodeList[this.codeindex] = code.checkedKeys;
      console.log(this.newcodeList);
    },
    check(index) {
      this.active = index;
    },
    checkj(index) {
      this.active1 = index;
    },
    // 打开标签
    addtag() {
      this.Eid = '';
      this.Tag = '新增标签';
      this.dialogTagVisible = true;
      this.CreateEmployeeTagInput = new CreateEmployeeTagInput();
      this.employeeTypeCode = [];
    },
    // 打开角色
    addrole() {
      this.creatorId = '';
      this.roletag = '新增角色';
      this.role = '';
      this.codeList = [];
      this.dialogRoleVisible = true;
      this.CreateRoleInput = new CreateEmployeeTagInput();
      this.$nextTick(() => {
        for (var i = 0; i < this.userList.length; i++) {
          console.log(this.userList[0].length);
          this.$refs.rightsTree[i].setCheckedKeys([]);
          for (var j = 0; j < this.userList[i].length; j++) {
            this.$refs.rightsTree[i].$children[j].node.parent.childNodes[j].expanded = false;
          }
        }
      });
    },
    // 获取角色
    getRoles() {
      const form = {
        IncludeDetails: true,
        MaxResultCount: 999,
        Sorting: 'creationTime DESC'
      };
      api_GET_Roles(form).then(res => {
        this.roles = res.items;
        console.log(this.roles);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取权限
    selectid() {
      this.codeList = [];
      this.$nextTick(() => {
        for (var i = 0; i < this.userList.length; i++) {
          console.log(this.userList[0].length);
          this.$refs.rightsTree[i].setCheckedKeys([]);
          for (var j = 0; j < this.userList[i].length; j++) {
            this.$refs.rightsTree[i].$children[j].node.parent.childNodes[j].expanded = false;
          }
        }
      });
      api_GET_RolesPermissionGroupsId(this.role).then(res => {
        for (var i = 0; i < res.length; i++) {
          for (var j = 0; j < res[i].children.length; j++) {
            this.codeList.push(res[i].children[j].code);
          }
        }
      });
      console.log(this.codeList);
    },
    // 添加角色
    editRoles(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.creatorId) {
            const shu = [];
            for (var i = 0; i < this.userList.length; i++) {
              shu.push(...this.$refs.rightsTree[i].getCheckedKeys());
            }
            this.CreateRoleInput.permissionGroupCodes = shu;
            console.log(this.CreateRoleInput);
            this.addroles = true;
            if (shu.length === 0) {
              this.$message({
                message: '请选择权限',
                type: 'warning'
              });
              this.addroles = false;
              return;
            }
            var num = this.CreateRoleInput.permissionGroupCodes.length;
            var head = [];
            for (var n = 0; n < num; n++) {
              head.push(this.CreateRoleInput.permissionGroupCodes[n].split('.')[0]);
            }
            const set = [...new Set(head)];
            for (var m = 0; m < set.length; m++) {
              this.CreateRoleInput.permissionGroupCodes.push(set[m] + '.Management');
            }
            this.CreateRoleInput.permissionGroupCodes = [...new Set(this.CreateRoleInput.permissionGroupCodes)];
            api_PUT_RolesUpdateId(this.creatorId, this.CreateRoleInput).then(res => {
              this.$message({
                message: '编辑成功',
                type: 'success'
              });
              this.creatorId = '';
              this.addroles = false;
              this.dialogRoleVisible = false;
              this.CreateRoleInput = new CreateRoleInput();
              this.codeList = [];
              this.getRoles();
              this.$nextTick(() => {
                for (var i = 0; i < this.userList.length; i++) {
                  this.$refs.rightsTree[i].setCheckedKeys(this.codeList);
                }
              });
            }, error => {
              this.creatorId = '';
              this.addroles = false;
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
              this.getRoles();
            });
          } else {
            const shu = [];
            for (var j = 0; j < this.userList.length; j++) {
              shu.push(...this.$refs.rightsTree[j].getCheckedKeys());
            }
            this.CreateRoleInput.permissionGroupCodes = shu;
            this.addroles = true;
            if (shu.length === 0) {
              this.$message(
                {
                  message: '请选择权限',
                  type: 'warning'
                });
              this.addroles = false;
              return;
            }
            var addnum = this.CreateRoleInput.permissionGroupCodes.length;
            var addhead = [];
            for (var addn = 0; addn < addnum; addn++) {
              addhead.push(this.CreateRoleInput.permissionGroupCodes[addn].split('.')[0]);
            }
            const set = [...new Set(addhead)];
            for (var addm = 0; addm < set.length; addm++) {
              this.CreateRoleInput.permissionGroupCodes.push(set[addm] + '.Management');
            }
            this.CreateRoleInput.permissionGroupCodes = [...new Set(this.CreateRoleInput.permissionGroupCodes)];
            api_POST_RolesCreate(this.CreateRoleInput).then(res => {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.addroles = false;
              this.role = '';
              this.dialogRoleVisible = false;
              this.CreateRoleInput = new CreateRoleInput();
              this.codeList = [];
              this.getRoles();
              this.$nextTick(() => {
                for (var i = 0; i < this.userList.length; i++) {
                  this.$refs.rightsTree[i].setCheckedKeys([]);
                }
              });
            }, error => {
              this.addroles = false;
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取树下标
    code(index) {
      this.codeindex = index;
    },
    // 编辑角色
    bianji(item) {
      this.roletag = '编辑角色';
      this.codeList = [];
      this.$nextTick(() => {
        for (var i = 0; i < this.userList.length; i++) {
          console.log(this.userList[0].length);
          this.$refs.rightsTree[i].setCheckedKeys([]);
          for (var j = 0; j < this.userList[i].length; j++) {
            this.$refs.rightsTree[i].$children[j].node.parent.childNodes[j].expanded = false;
          }
        }
      });
      this.dialogRoleVisible = true;
      this.creatorId = item.id;
      this.CreateRoleInput.displayName = item.displayName;
      this.CreateRoleInput.description = item.description;
      this.role = item.displayName;
      api_GET_RolesPermissionGroupsId(item.id).then(res => {
        for (var i = 0; i < res.length; i++) {
          for (var j = 0; j < res[i].children.length; j++) {
            this.codeList.push(res[i].children[j].code);
          }
        }
      });
      console.log(this.codeList);
    },
    // 删除角色
    deleteRole(item) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_RolesId(item.id).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getRoles();
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
    },
    downRoles() {
      this.dialogRoleVisible = false;
      this.CreateRoleInput = new CreateRoleInput();
      this.codeList = [];
      this.$nextTick(() => {
        for (var i = 0; i < this.userList.length; i++) {
          this.$refs.rightsTree[i].setCheckedKeys(this.codeList);
        }
      });
    },
    downEmployee() {
      this.Eid = '';
      this.dialogTagVisible = false;
      this.CreateEmployeeTagInput = new CreateEmployeeTagInput();
      this.employeeTypeCode = [];
      this.getEmploy();
    },
    // 添加标签
    addEmployee(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.Eid) {
            this.addtagg = true;
            this.CreateEmployeeTagInput.employeeTypeCodes = this.employeeTypeCode;
            console.log(this.employeeTypeCode);
            api_PUT_ClubEmployeeTagId(this.Eid, this.CreateEmployeeTagInput).then(res => {
              this.$message({
                message: '编辑成功',
                type: 'success'
              });
              this.addtagg = false;
              this.dialogTagVisible = false;
              this.CreateEmployeeTagInput = new CreateEmployeeTagInput();
              this.employeeTypeCode = [];
              this.getEmploy();
              this.Eid = '';
            }, error => {
              this.addtagg = false;
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          } else {
            this.addtagg = true;
            this.CreateEmployeeTagInput.employeeTypeCodes = this.employeeTypeCode;
            console.log(this.employeeTypeCode);
            api_POST_ClubEmployeeTag(this.CreateEmployeeTagInput).then(res => {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.addtagg = false;
              this.dialogTagVisible = false;
              this.CreateEmployeeTagInput = new CreateEmployeeTagInput();
              this.employeeTypeCode = [];
              this.getEmploy();
            }, error => {
              this.addtagg = false;
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取标签
    getEmploy() {
      this.Api_GET_ClubEmployeeTagQO.IncludeEmployeeTagEmployeeTypes = true; // type: boolean
      this.Api_GET_ClubEmployeeTagQO.IncludeEmployeeEmployeeTags = true; // type: boolean
      this.Api_GET_ClubEmployeeTagQO.Sorting = 'creationTime DESC';
      api_GET_ClubEmployeeTag(this.Api_GET_ClubEmployeeTagQO).then(res => {
        console.log(res);
        this.employees = res.items;
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 删除标签
    deleteE(item) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubEmployeeTagId(item.id).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getEmploy();
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
    },
    // 编辑标签
    editE(item) {
      this.Tag = '编辑标签';
      // 获取指定员工
      this.Eid = item.id;
      this.employeeTypeCode = [];
      this.Api_GET_ClubEmployeeTagIdQO.IncludeEmployeeTagEmployeeTypes = true;
      this.Api_GET_ClubEmployeeTagIdQO.IncludeEmployeeEmployeeTags = true;
      api_GET_ClubEmployeeTagId(item.id, this.Api_GET_ClubEmployeeTagIdQO).then((res) => {
        this.CreateEmployeeTagInput.name = res.name;
        this.CreateEmployeeTagInput.description = res.description;
        for (var i = 0; i < res.employeeTagEmployeeTypes.length; i++) {
          this.employeeTypeCode.push(res.employeeTagEmployeeTypes[i].employeeTypeCode);
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
        this.Eid = '';
      });
      this.dialogTagVisible = true;
    },
    // 查看权限
    permissions(item) {
      this.$refs.permiss.description = item.description;
      this.$refs.permiss.name = item.displayName;
      this.$refs.permiss.staffId = item.id;
      this.$refs.permiss.dialogVisible = true;
      this.$refs.permiss.codeList = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.nav{
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
}
 ::v-deep .el-card__header{
   background-color: rgba(64,158,255,0.06);
   border-bottom: 0px;
 }
 .yuan{
   display: inline-block;
   width: 8px;
   height: 8px;
   border-radius: 50%;
   background-color: red;
   margin-right: 8PX;
 }
  .fang{
   display: inline-block;
   width: 8px;
   height: 8px;
   background-color: rgb(158, 152, 152);
   margin-right: 8PX;
 }
 .tree{
   display: flex;
   flex-wrap: wrap;
   overflow: hidden;
 }
::v-deep .el-tree-node__content {
   height: 35px;
 }

::v-deep .el-form-item__label{
     color: #999999;
     font-size: 14px;
  }
  .table_name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  }
::v-deep .btn{
  align-items: center;
  margin-top:3px;
  .el-button {
    padding: 0px;
  }
}
</style>
